/*
 * @Author: kanglang
 * @Date: 2020-11-23 18:02:07
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-07-02 11:42:01
 * @Description: 绑定手机
 */
import React, { Component, Fragment } from 'react';
import {
  StyleSheet, Text, TextInput, TouchableOpacity, View,
  NativeModules, ScrollView, findNodeHandle, Dimensions,
  DeviceEventEmitter,
  SafeAreaView,
  BackHandler
} from 'react-native';
import user from '@/api/user';
import { msg, XMHeader, cache, SendMsgCode, AsyncStorage, BackImage } from '@/common';
import { px2dp, screenWidth, isAndroid } from '@/styles';
import { loginAlert, checkMobile } from '@/common/util';
import homeApi from '@/api/home';
import { getAgreementByArray, checkUserAgreement } from '@/common/agreement-version';
import XmInput from '../components/xm-input';
import LoginBtn from '../components/login-btn';
import FirstLoadAPP from '../components/first-loadapp';

class MobileBind extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mobile: '',
      code: '',
      keyboardHeight: 0,
      isShowAgreement: false,
      agreementList: [],
    };
  }

  UNSAFE_componentWillMount() {
    this._keyboardDidHide();
  }

  componentDidMount() {
    // 处理安卓物理返回键
    if (Platform.OS === 'android') {
      BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
    }
  }

  componentWillUnmount() {
    if (Platform.OS === 'android') {
      BackHandler.removeEventListener(
        'hardwareBackPress',
        this.handleBackPress,
      );
    }
  }

  // 处理安卓物理返回键
  handleBackPress = () => {
    return true;
  };

  _keyboardDidShow(e) {
    console.log(e, '键盘高度');
    this.setState({
      keyboardHeight: e.endCoordinates.height
    });
  }

  _keyboardDidHide(e) {
    this.setState({
      keyboardHeight: 0
    });
  }

  scrollViewTo(e) {
    let { target } = e.nativeEvent;
    let scrollLength = 0;// 初始值
    if (target === findNodeHandle(this.refs.hour) || target === findNodeHandle(this.refs.name)) {
      scrollLength = this.state.keyboardHeight;
    }
    this.refs.scroll.scrollTo({ y: scrollLength, x: 0 });
    console.log(scrollLength, '移动的高度');
  }

  onPressLogin = () => {
    const { mobile, code } = this.state;
    // 查询隐私协议版本
    getAgreementByArray(
      ['agreement', 'privacyAgreement', 'PerInfoAgreement'],
      (data) => {
        this.setState({ agreementList: data }, () => {
          checkUserAgreement(
            mobile,
            data,
            (isShow) => {
              if (isShow) {
                // 弹窗
                this.setState({ isShowAgreement: true });
              } else {
                this.nextStepAction();
              }
            },
          );
        });
      },
    );
  }

  onChangeText = (name, value) => {
    this.setState({ [name]: value });
  }

  render() {
    const { mobile, code, isShowAgreement, agreementList } = this.state;
    const isActive = (mobile !== '' && mobile.length === 11) && (code !== '' && code.length === 4);
    return (
      <SafeAreaView style={{ flex: 1 }}>
        {/* <Header
          title='绑定手机号'
          renderLeft={() => {
            return (
              <TouchableOpacity
                activeOpacity={0.8}
                style={isAndroid ? { paddingVertical: px2dp(14), paddingHorizontal: px2dp(40) } :
                  { paddingVertical: px2dp(14), paddingRight: px2dp(40) }}
                onPress={() => {
                  msg.emit('router: back');
                }}>
                <BackImage />
              </TouchableOpacity>
            );
          }}
          renderRight={() => { }}
        /> */}
        <ScrollView
          style={{ backgroundColor: '#fff' }}
          keyboardShouldPersistTaps='always'
          ref='scroll'
        >
          <View style={styles.container}>
            <View
              style={{ marginTop: 40 }}
              onStartShouldSetResponderCapture={(e) => { }}
            >
              <View style={styles.bindWrap}>
                <Text style={styles.bindPhone}>绑定手机号</Text>
                <Text style={styles.needBid}>需绑定手机号才能进行登录</Text>
              </View>
              <View style={{ marginTop: px2dp(80) }}>
                <XmInput
                  name='mobile'
                  placeholder='手机号'
                  onChange={this.onChangeText}
                />
                <View style={styles.pwdWrap}>
                  <XmInput
                    name='code'
                    placeholder='验证码'
                    onChange={this.onChangeText}
                  />
                  <SendMsgCode
                    frameStyle={styles.sendBtn}
                    count={60}
                    pressAction={this.sendMsgCode}
                    changeWithCount={(count) => `${count}s后重试`}
                    id='bindMobile'
                    ref={(e) => { this.countDownButton = e; }}
                  />
                </View>
              </View>
            </View>
            <LoginBtn
              disabled={!isActive}
              isActive={isActive}
              btnText='下一步'
              submit={this.onPressLogin}
            />
          </View>
        </ScrollView>
        {
          isShowAgreement &&
          <FirstLoadAPP
            articlesList={agreementList}
            onDisappear={this.firstLoadDisappear}
          />
        }
      </SafeAreaView>
    );
  }

  // 处理安卓物理返回键
  handleBackPress = () => {
    return true;
  };

  _keyboardDidShow(e) {
    console.log(e, '键盘高度');
    this.setState({
      keyboardHeight: e.endCoordinates.height
    });
  }

  _keyboardDidHide(e) {
    this.setState({
      keyboardHeight: 0
    });
  }

  scrollViewTo(e) {
    let { target } = e.nativeEvent;
    let scrollLength = 0;// 初始值
    if (target === findNodeHandle(this.refs.hour) || target === findNodeHandle(this.refs.name)) {
      scrollLength = this.state.keyboardHeight;
    }
    this.refs.scroll.scrollTo({ y: scrollLength, x: 0 });
    console.log(scrollLength, '移动的高度');
  }

  nextStepAction = () => {
    const { mobile, code, agreementList } = this.state;
    let type = 1;
    if (Platform.OS === 'ios') {
      type = 2;
    }
    msg.emit('app:messageBox', {
      isVisible: true,
      title: '温馨提示',
      text: '即将修改当前手机号码绑定的微信账号为当前登录微信账号，请确认',
      okText: '确认',
      cancelText: '取消',
      isClickBg: false,
      okFn: () => {
        user.weixinRegister({
          mobile,
          code,
          registerWay: type
        }).then(res => {
          if (res.success) {
            user.getUserInfo().then(res => {
              console.log(res);
              if (res.success) {
                AsyncStorage.setItem(cache.USER_INFO, res.data);
                let params = [];
                agreementList.map(item => {
                  params.push({
                    dealCode: item.contentCode,
                    dealContent: item.contentInfo,
                    versionNum: item.versionNum,
                    dealTitle: item.contentTitle,
                  });
                });
                user.addUserDeal(params);
                DeviceEventEmitter.emit('UPDATE_INTEGRAL', true);
                msg.emit('router: goToNext', {
                  routeName: 'Mine'
                });
              } else {
                loginAlert();
              }
            });
          } else {
            NativeModules.WindowModule.showWindow({ content: res.msg, onlyRightBtn: '1' }, (e) => { });
          }
        }).catch(res => {
          NativeModules.WindowModule.showWindow({ content: '绑定失败，请稍后重试', onlyRightBtn: '1' }, (e) => { });
        });
      },
    });
  }

  getAR = (code) => {
    return homeApi.getTextProtol({ code });
  }

  _handleBack() {
    const { navigator } = this.props;
    if (navigator && navigator.getCurrentRoutes().length > 1) {
      navigator.pop();
      return true;
    }
    return false;
  }

  sendMsgCode = () => {
    const { mobile } = this.state;
    const isMobile = checkMobile(mobile);
    if (!mobile || (mobile.length < 11 && !isMobile)) {
      NativeModules.WindowModule.showWindow({
        content: '请输入正确的手机号码',
        onlyRightBtn: '1'
      }, (e) => { });
      return;
    }
    user.chekeWxBymobile({ mobile }).then(res => {
      if (res.success && res.data) {
        // 已绑定
        msg.emit('app:messageBox', {
          isVisible: true,
          title: '温馨提示',
          text: '当前手机号码已经绑定其他微信，是否需要更换微信绑定',
          okText: '下一步',
          cancelText: '取消',
          isClickBg: false,
          okFn: () => {
            this.sendMsg();
          },
        });
      } else {
        // 未绑定
        this.sendMsg();
      }
    });
  }

  // 发送短信
  sendMsg = () => {
    const { mobile } = this.state;
    this.countDownButton.startCountDown(() => {
      user.requireSmsCode({ mobile, terminalCode }).then(res => {
        if (!res.success) {
          NativeModules.WindowModule.showWindow({
            content: '验证码发送失败',
            onlyRightBtn: '1'
          }, (e) => { });
        }
      });
    });
  }

  firstLoadDisappear = (isAgree) => {
    this.setState({ isShowAgreement: false });
    if (isAgree) {
      this.nextStepAction();
    }
  }

  render() {
    const { mobile, code, isShowAgreement, agreementList } = this.state;
    const isActive = (mobile !== '' && mobile.length === 11) && (code !== '' && code.length === 4);
    return (
      <SafeAreaView style={{ flex: 1 }}>
        <XMHeader
          title='绑定手机号'
          renderLeft={() => {
            return (
              <TouchableOpacity
                activeOpacity={0.8}
                style={isAndroid ? { paddingVertical: px2dp(14), paddingHorizontal: px2dp(40) } :
                  { paddingVertical: px2dp(14), paddingRight: px2dp(40) }}
                onPress={() => {
                  msg.emit('router: back');
                }}
              >
                <BackImage />
              </TouchableOpacity>
            );
          }}
          renderRight={() => { }}
        />
        <ScrollView
          style={{ backgroundColor: '#fff' }}
          keyboardShouldPersistTaps='always'
          ref='scroll'
        >
          <View style={styles.container}>
            <View
              style={{ marginTop: 40 }}
              onStartShouldSetResponderCapture={(e) => { }}
            >
              <View style={styles.bindWrap}>
                <Text style={styles.bindPhone}>绑定手机号</Text>
                <Text style={styles.needBid}>需绑定手机号才能进行登录</Text>
              </View>
              <View style={{ marginTop: px2dp(80) }}>
                <XmInput
                  name='mobile'
                  placeholder='手机号'
                  onChange={this.onChangeText}
                />
                <View style={styles.pwdWrap}>
                  <XmInput
                    name='code'
                    placeholder='验证码'
                    onChange={this.onChangeText}
                  />
                  <SendMsgCode
                    frameStyle={styles.sendBtn}
                    count={60}
                    pressAction={this.sendMsgCode}
                    changeWithCount={(count) => `${count}s后重试`}
                    id='bindMobile'
                    ref={(e) => { this.countDownButton = e; }}
                  />
                </View>
              </View>
            </View>
            <LoginBtn
              disabled={!isActive}
              isActive={isActive}
              btnText='下一步'
              submit={this.onPressLogin}
            />
          </View>
        </ScrollView>
        {isShowAgreement && <FirstLoadAPP
          articlesList={agreementList}
          onDisappear={this.firstLoadDisappear}
        />}
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#ffffff',
    alignItems: 'center'
  },
  pwdWrap: {
    width: '100%',
    marginTop: px2dp(20),
    justifyContent: 'center'
  },
  sendBtn: {
    position: 'absolute',
    right: 0,
    borderWidth: 0,
    fontSize: px2dp(28),
    backgroundColor: 'transparent',
  },
  bindPhone: {
    color: '#333232',
    fontSize: 22
  },
  needBid: {
    color: '#999796',
    fontSize: 14,
    marginTop: 6
  },
  bindWrap: {
    paddingHorizontal: px2dp(24)
  }
});

export default MobileBind;
